package com.fjl;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.indices.CreateIndexRequest;
import co.elastic.clients.elasticsearch.indices.CreateIndexResponse;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

@Configuration
public class ElasticsearchConfig {

    @Value("${spring.elasticsearch.uris}")
    private String elasticsearchUrl;

    @Bean
    public ElasticsearchClient elasticsearchClient() {
        // 使用 RestClientBuilder 来创建连接
        RestClientBuilder builder = RestClient.builder(HttpHost.create(elasticsearchUrl));

        // 构建 RestClient
        RestClient restClient = builder.build();

        // 创建 Transport 对象，使用 JacksonJsonpMapper 进行 JSON 解析
        RestClientTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());

        // 返回 ElasticsearchClient 实例
        ElasticsearchClient elasticsearchClient = new ElasticsearchClient(transport);

        return elasticsearchClient;
    }
    public void createIndexWithNoReplica( ElasticsearchClient elasticsearchClient) throws IOException {
        String indexName = "file_index";  // 你的索引名

        // 检查索引是否存在，如果不存在则创建
        boolean indexExists = elasticsearchClient.indices().exists(e -> e.index(indexName)).value();
        if (!indexExists) {
            CreateIndexRequest createIndexRequest = new CreateIndexRequest.Builder()
                    .index(indexName)
                    .settings(settings -> settings
                            .numberOfShards(String.valueOf(1))
                            .numberOfReplicas(String.valueOf(0)))  // 设置副本数为0
                    .build();

            CreateIndexResponse response = elasticsearchClient.indices().create(createIndexRequest);
            System.out.println("Index created: " + response.index());
        } else {
            System.out.println("Index already exists: " + indexName);
        }
    }
}
